﻿<html>
<head>
<meta charset="utf-8">
<title>行情图表</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link href="css/reset.css" rel="stylesheet" type="text/css"/>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script src="js/fontSize.js"></script>
<script src="js/echarts.min.js"></script>
<script src="https://cdn.hcharts.cn/highcharts/highcharts.js"></script>
<script src="js/vue.min.js"></script>
</head>
<body>

<div class="page" id="app">

  <div class="top-price new-price">
    <div class="top-lt">
      <div class="lt-num"><b>￥{{info.newestPrice || 0}}</b>+{{info.coinGain || 0}}%</div>
      <div class="lt-price">≈{{info.usd || '0.00'}} USD</div>
    </div>
    <ul class="top-rg">
      <li><span>最高</span>{{curInfo.max || '0.00'}}</li>
      <li><span>最低</span>{{curInfo.min || '0.00'}}</li>
      <li><span>24H</span>{{curInfo.total || 0}}</li>
    </ul>
  </div>

  <div class="main-box new-box">
    <div class="main-list new-list">
      <span :class='type==1 ? "cur" : ""' @click='getType(1, 1)'>分时</span>
      <span :class='type==2 ? "cur" : ""' @click='getType(2, 15)'>15分</span>
      <span :class='type==3 ? "cur" : ""' @click='getType(3, 60)'>1小时</span>
      <span :class='type==4 ? "cur" : ""' @click='getType(4, 240)'>4小时</span>
      <span :class='type==5 ? "cur" : ""' @click='getType(5, 1440)'>日线</span>
      <span :class='type==6 ? "cur" : ""' @click='getType(6)'>更多<img src="img/icon-down2.png"></span>
      <span :class='type==7 ? "cur" : ""' @click='getType(7)'>指标<img src="img/icon-down2.png"></span>
    </div>
    <div class="main-type" v-if='type==6'>
      <div class="type-li">
        <span :class='newType==1 ? "cur" : ""' @click='getNewType(1, 1)'>1分</span>
        <span :class='newType==2 ? "cur" : ""' @click='getNewType(2, 5)'>5分</span>
        <span :class='newType==3 ? "cur" : ""' @click='getNewType(3, 30)'>30分</span>
        <span :class='newType==4 ? "cur" : ""' @click='getNewType(4, 120)'>2小时</span>
        <span :class='newType==5 ? "cur" : ""' @click='getNewType(5, 480)'>8小时</span>
        <span :class='newType==6 ? "cur" : ""' @click='getNewType(6, 10080)'>周线</span>
        <span :class='newType==7 ? "cur" : ""' @click='getNewType(7)'>月线</span>
      </div>
    </div>
    <div class="main-type" v-if='type==7'>
      <div class="type-li">
        <span class="name">主指标</span>
        <span class="cur">MA</span>
        <span>EMA</span>
        <span>BOLL</span>
      </div>
      <div class="type-li">
        <span class="name">副指标</span>
        <span class="cur">MACD</span>
        <span>KDJ</span>
        <span>RSI</span>
      </div>
    </div>
    <div id="main"></div>
  </div>

</div>

<script src="js/axios.min.js"></script>
<script>
//获取屏幕的宽度
var clientWidth = document.documentElement.clientWidth;
//根据设计图中的canvas画布的占比进行设置
var canvasHeight = Math.floor(clientWidth*912/750);
console.log(canvasHeight);
document.getElementById('main').setAttribute('height', canvasHeight+'px');

var myChart = null;
var flag = false;//月线图
new Vue({
  el: '#app',
  data: {
    type: 1,
    newType: 1,
    botType: 1,
    rate: 1, //汇率
    info: {}, //币种信息
    curInfo: {}, //最新信息
    deepArr: {},
    tradeArr: [],
    //k线图数据
    kData: {
      datas: [],
      times: [],
      vols: [],
      macds: [],
      difs: [],
      deas: []
    }
  },
  methods: {
    getType:function(type, num){
      this.type = type;
      if(type==6){
        this.newType = 1;
        this.kline(60);
      }
      else if(type==7){

      }
      else{
        var min = num * 60;
        this.kline(min);
      }
    },
    getNewType:function(type, num){
      this.newType = type;
      if(type==7){
        this.kline(1, true);
      }
      else{
        var min = num * 60;
        this.kline(min);
      }
    },
    kline:function(min, flag){
      //分线图
      var self = this;
      var kData = {
        datas: [],
        times: [],
        vols: [],
        macds: [],
        difs: [],
        deas: []
      };
      var url = "/front/kline/minute";
      var params = {
        pageNum: 1,
        minuteCount: min || 60
      };
      if(flag){
        url = "/front/kline/month";
        params = {
          pageNum: 1
        };
      }

      //收盘价
      var closeArr = [];
      axios.get(api + url, {
        params: params
      })
      .then(function (res) {
        if(res.data.code == 0){
          console.log(res.data)
          var newArr = res.data.data;
          var len = newArr.length;
          //time0 open1 close2 min3 max4 vol5 tag6 macd7 dif8 dea9
          for(var i=0;i<len;i++){
            kData.datas.push(
              [newArr[i].startPrice, newArr[i].endPrice, newArr[i].lowestPrice, newArr[i].highestPrice, newArr[i].gain, newArr[i].gain, newArr[i].gain, newArr[i].gain, newArr[i].dealCount]
            );
            closeArr.push(newArr[i].endPrice);
            kData.times.push(newArr[i].time.slice(0,10));
            kData.vols.push(newArr[i].dealCount);
            //kData.macds.push(newArr[i].dealCount);
            //kData.difs.push(newArr[i].dealCount);
            //kData.deas.push(newArr[i].dealCount);
          }
          //计算指标
          //差离值
          //difs: EMA(12) - EMA(26)
          var difs = [];
          var ema1 = EMA(closeArr, 12);
          var ema2 = EMA(closeArr, 26);
          for(var j=0,jlen=ema1.length;j<jlen;j++){
            var thisVal = (ema1[j] - ema2[j]) ? (ema1[j] - ema2[j]).toFixed(2) : 0;
            difs.push(thisVal)
          }
          console.log(difs)

          //离差平均值
          //deas: EMA(9)
          var deas = EMA(difs, 9);
          console.log(deas)

          //MACD = （DIF-DEA）*2
          var macd = [];
          for(var k=0,klen=difs.length;k<klen;k++){
            var thisVal = (difs[k] - deas[k]) ? (difs[k] - deas[k]).toFixed(2) : 0;
            macd.push(thisVal)
          }
          console.log(macd)

          kData.difs = difs;
          kData.deas = deas;
          kData.macds = macd;
          self.kData = kData;
          //console.log(kData.datas)
          //一共50条 分两部分;
          //先显示前25条,左滑显示后25条;
          //超过50条 左滑 pageNum + 1
          self.showChart(1);
        }
      })
      .catch(function (error) {
        console.log(error);
      });
      function EMA(data, day){
        var result = [];
        for (var i = 0, len = data.length; i < len; i++) {
            if (i < day) {
                result.push('-');
                continue;
            }
            var sum = 0;
            for (var j = 0; j < day; j++) {
                sum += kData.datas[i - j][1];
            }
            result.push((sum / day).toFixed(2));
        }
        return result;
      }
    },
    mline:function(){
      //月线图
      axios.get(api + "/front/kline/month", {
        params: {
          pageNum: 1
        }
      })
      .then(function (res) {
        if(res.data.code == 0){
          console.log(res.data)
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    },
    //数据渲染
    showChart:function(num){
      var newData = this.kData;
      var kData = {
        datas: [],
        times: [],
        vols: [],
        macds: [],
        difs: [],
        deas: []
      };
      if(num==1){
        for(var i=25,len=newData.datas.length;i<len;i++){
          kData.datas.push(newData.datas[i]);
          kData.times.push(newData.times[i]);
          kData.vols.push(newData.vols[i]);
          kData.macds.push(newData.macds[i]);
          kData.difs.push(newData.difs[i]);
          kData.deas.push(newData.deas[i]);
        }
      }
      else{
        for(var i=0,len=newData.datas.length;i<25;i++){
          kData.datas.push(newData.datas[i]);
          kData.times.push(newData.times[i]);
          kData.vols.push(newData.vols[i]);
          kData.macds.push(newData.macds[i]);
          kData.difs.push(newData.difs[i]);
          kData.deas.push(newData.deas[i]);
        }
      }
      var option = {
        backgroundColor: '#fff',
        tooltip: {
            //show: false,
            trigger: 'axis',
            axisPointer: {
                type: 'line'
            },
            //trigger: 'item',
            formatter: function (params) {
              if(params[0].seriesName=="K线图"){
                console.log(params)
                var htmlStr ='<div class="k-box">';
                htmlStr += "<div class='k-li'><span>时间</span><span>" + params[0].name + '</span></div>';
                htmlStr += "<div class='k-li'><span>开盘</span><span>" + params[0].data[1] + '</span></div>';
                htmlStr += "<div class='k-li'><span>收盘</span><span>" + params[0].data[2] + '</span></div>';
                htmlStr += "<div class='k-li'><span>最高</span><span>" + params[0].data[3] + '</span></div>';
                htmlStr += "<div class='k-li'><span>最低</span><span>" + params[0].data[4] + '</span></div>';
                htmlStr += "<div class='k-li'><span>涨跌幅</span><span>" + params[0].data[5] + '%</span></div>';
                htmlStr += "<div class='k-li'><span>成交量</span><span>" + params[0].data[9] + '</span></div></div>';
                return htmlStr;
              }
            }
        },
        legend: {
            show: false,
            data: ['KLine', 'MA5']
        },
        grid: [           
        {
            left: '1%',
            right: '1%',
            height: '50%',
            borderWidth: 0,
            containLabel: true
        },{
            left: '1%',
            right: '1%',
            top: '70%',
            height: '12%'
        },{
            left: '1%',
            right: '1%',
            top: '85%',
            height: '10%'
        }],
        xAxis: [{
            type: 'category',
            data: kData.times,
            scale: true,
            boundaryGap: false,
            axisLine: {
              show: false,
              onZero: false 
            },
            axisTick: {
              show: false
            },
            splitLine: { 
              show: false,
              lineStyle: {
                color: '#ECECEC'
              }
            },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            axisLabel: {
              show: true,
              align: 'left',
              textStyle: {
                color: '#8F8F8F'
              }
            }
        },{
            type: 'category',
            gridIndex: 1,
            data: kData.times,
            axisLabel: {
              show: false
            },
            axisLine: {
              show: true,
              onZero: false,
              lineStyle: {
                color: '#ECECEC'
              }
            },
            axisTick: {
              show: false
            },
            splitLine: { 
              show: false,
              lineStyle: {
                color: '#ECECEC'
              }
            }
        },{
            type: 'category',
            gridIndex: 2,
            data: kData.times,
            axisLabel: {
              show: true,
              align: 'left',
              textStyle: {
                color: '#8F8F8F'
              }
            },
            axisLine: {
              show: true,
              onZero: false,
              lineStyle: {
                color: '#ECECEC'
              }
            },
            axisTick: {
              show: false
            },
            splitLine: { 
              show: false,
              lineStyle: {
                color: '#ECECEC'
              }
            }
        }],
        yAxis: [{
            scale: true,
            splitLine: { 
              show: true,
              lineStyle: {
                color: '#ECECEC'
              }
            },
            splitArea: {
                show: false
            },
            position: 'left',
            axisLine: {
              show: false,
              onZero: false 
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#B9B9B9'
              }
            }
        },{
            gridIndex: 1,
            splitNumber: 1,
            axisLine: {
              show: false,
              onZero: false,
              lineStyle: {
                color: '#ECECEC'
              }
            },
            axisTick: {show: false},
            splitLine: { 
              show: true,
              lineStyle: {
                color: '#ECECEC'
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#B9B9B9'
              }
            }
        },{
            gridIndex: 2,
            splitNumber: 1,
            axisLine: {
              show: false,
              onZero: false,
              lineStyle: {
                color: '#ECECEC'
              }
            },
            axisTick: {show: false},
            splitLine: { 
              show: true,
              lineStyle: {
                color: '#ECECEC'
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#B9B9B9'
              }
            }
        }],
        dataZoom: [{
            show: false,
            xAxisIndex: [0, 2],
            type: 'slider',
            start: 20,
            end: 100
        }],
        series: [{
                name: 'K线图',
                type: 'candlestick',
                data: kData.datas,
                itemStyle: {
                    normal: {
                      color: '#ef232a',
                      color0: '#14b143',
                      borderColor: '#ef232a',
                      borderColor0: '#14b143'
                    }
                }
            }, {
                name: 'MA5',
                type: 'line',
                data: calculateMA(5),
                smooth: true,
                lineStyle: {
                    normal: {
                        opacity: 0.5
                    }
                }
            },{
                name: 'Volumn',
                type: 'bar',
                xAxisIndex: 1,
                yAxisIndex: 1,
                data: kData.vols,
                itemStyle: {
                normal: {
                    color: function(params) {
                        var colorList;
                        if (kData.datas[params.dataIndex][1]>kData.datas[params.dataIndex][0]) {
                            colorList = '#ef232a';
                        } else {
                            colorList = '#14b143';
                        }
                        return colorList;
                    },
                }
              }
            },{
                name: 'MACD',
                type: 'bar',
                xAxisIndex: 2,
                yAxisIndex: 2,
                data: kData.macds,
                itemStyle: {
                normal: {
                    color: function(params) {
                        var colorList;
                        if (params.data >= 0) {
                            colorList = '#ef232a';
                        } else {
                            colorList = '#14b143';
                        }
                        return colorList;
                    },
                }
              }
            },{
                name: 'DIF',
                type: 'line',
                xAxisIndex: 2,
                yAxisIndex: 2,
                data: kData.difs
            },{
                name: 'DEA',
                type: 'line',
                xAxisIndex: 2,
                yAxisIndex: 2,
                data: kData.deas
            }
        ]
      };
      myChart.setOption(option);
      //MA计算公式
      function calculateMA(dayCount) {
        var result = [];
        for (var i = 0, len = kData.times.length; i < len; i++) {
            if (i < dayCount) {
                result.push('-');
                continue;
            }
            var sum = 0;
            for (var j = 0; j < dayCount; j++) {
                sum += kData.datas[i - j][1];
            }
            result.push((sum / dayCount).toFixed(2));
        }
        return result;
      }
    }
  },
  created:function(){
    var self = this;

    //获取汇率
    axios.get(api + "/front/info/exchangeRate", {
      params: {}
    })
    .then(function (res) {
      if(res.data.code == 0){
        self.rate = res.data.data
      }
    })
    .catch(function (error) {
      console.log(error);
    });

    //获取币种信息
    axios.get(api + "/front/info/coin", {
      params: {
        coinTypeId: 1
      }
    })
    .then(function (res) {
      if(res.data.code == 0){
        self.info = res.data.data;
        self.info.usd = res.data.data.newestPrice.toFixed(2);
      }
    })
    .catch(function (error) {
      console.log(error);
    });

    //今日价格、成交量
    //获取当前时间的分钟数
    var now = new Date();
    var curMins = now.getHours() * 60 + now.getMinutes();
    axios.get(api + "/front/kline/minute", {
      params: {
        pageNum: 1,
        minuteCount: curMins
      }
    })
    .then(function (res) {
      if(res.data.code == 0){
        var newArr = res.data.data;
        var total = 0;
        for(var i=0,len=newArr.length;i<len;i++){
          total += (newArr[i].dealCount || 0)
        }
        self.curInfo = {
          max: newArr[newArr.length - 1].highestPrice,
          min: newArr[newArr.length - 1].lowestPrice,
          total: total.toFixed(2)
        }
      }
    })
    .catch(function (error) {
      console.log(error);
    });

    //分线图
    self.kline(60);

  },
  mounted:function(){
    var self = this;
    //重要！禁止移动端滑动的默认事件
    document.body.addEventListener('touchmove', function(event) {
        event = event ? event : window.event;
        if(event.preventDefault) {
            event.preventDefault()
        } else {
            event.returnValue = false
        }
    }, false)

    //左滑
    var startY, moveY, cliH, moveX, startX;
    //touchStart
    var touchstart = function(event) {
        if(!event.touches.length) {
            return;
        }
        startY = event.touches[0].pageY;
        moveY = 0;
        startX = event.touches[0].pageX;
        moveX = 0;
    };
    //touchMove
    var touchmove = function(event) {
        if(!event.touches.length) {
            return;
        }
        moveY = event.touches[0].pageY - startY;
        moveX = event.touches[0].pageX - startX;
    };
    //touchEnd
    var touchend = function(event) {
      //监听左滑
      console.log(moveX)
      if(moveX > 200){
        console.log("左滑")
        self.showChart(2);
      }
    }
    var box = document.getElementById("main");
    //touch事件绑定
    box.addEventListener("touchstart", function(event) {
        touchstart(event)
    }, false);
    box.addEventListener("touchmove", function(event) {
        touchmove(event)
    }, false);
    box.addEventListener("touchend", function(event) {
        touchend(event)
    }, false);

    //K线图
    var self = this;
    myChart = echarts.init(document.getElementById('main'));
    myChart.resize({
      height: canvasHeight+'px'
    })
    //数据模型 time0 open1 close2 min3 max4 vol5 tag6 macd7 dif8 dea9
    //['2015-10-19',18.56,18.25,18.19,18.56,55.00,0,-0.00,0.08,0.09] 
    // var data = splitData([
    //   ['2015-10-16',18.4,18.58,18.33,18.79,67.00,1,0.04,0.11,0.09],
    //   ['2015-10-19',18.56,18.25,18.19,18.56,55.00,0,-0.00,0.08,0.09],
    //   ['2015-10-20',18.3,18.22,18.05,18.41,37.00,0,0.01,0.09,0.09],
    //   ['2015-10-21',18.18,18.69,18.02,18.98,89.00,0,0.03,0.10,0.08],
    //   ['2015-10-22',18.42,18.29,18.22,18.48,43.00,0,-0.06,0.05,0.08],
    //   ['2015-10-23',18.26,18.19,18.08,18.36,46.00,0,-0.10,0.03,0.09],
    //   ['2015-10-26',18.33,18.07,17.98,18.35,65.00,0,-0.15,0.03,0.10]
    // ]);
    //console.log(data)

    // this.data = {
    //   datas: datas,
    //   times: times,
    //   vols: vols,
    //   macds: macds,
    //   difs: difs,
    //   deas: deas
    // };

    var data = self.kData;
    //数组处理
    function splitData(rawData) {
      var datas = [];
      var times = [];
      var vols = [];
      var macds = []; var difs = []; var deas = [];
      for (var i = 0; i < rawData.length; i++) {
        datas.push(rawData[i]);
        times.push(rawData[i].splice(0, 1)[0]);
        vols.push(rawData[i][4]);
        macds.push(rawData[i][6]);
        difs.push(rawData[i][7]);
        deas.push(rawData[i][8]);
      }
      return {
          datas: datas,
          times: times,
          vols: vols,
          macds: macds,
          difs: difs,
          deas: deas
      };
    }

    //分段计算
    function fenduans(){
      var markLineData = [];
      var idx = 0; var tag = 0; var vols = 0;
      for (var i = 0; i < data.times.length; i++) {
        //初始化数据
          if(data.datas[i][5] != 0 && tag == 0){
              idx = i; vols = data.datas[i][4]; tag = 1;
          }
          if(tag == 1){ vols += data.datas[i][4]; }
          if(data.datas[i][5] != 0 && tag == 1){
              markLineData.push([{
                  xAxis: idx,
                  yAxis: data.datas[idx][1]>data.datas[idx][0]?(data.datas[idx][3]).toFixed(2):(data.datas[idx][2]).toFixed(2),
                  value: vols
              }, {
                  xAxis: i,
                  yAxis: data.datas[i][1]>data.datas[i][0]?(data.datas[i][3]).toFixed(2):(data.datas[i][2]).toFixed(2)
              }]);
              idx = i; vols = data.datas[i][4]; tag = 2;
          }
          
          //更替数据
          if(tag == 2){ vols += data.datas[i][4]; }
          if(data.datas[i][5] != 0 && tag == 2){
              markLineData.push([{
                  xAxis: idx,
                  yAxis: data.datas[idx][1]>data.datas[idx][0]?(data.datas[idx][3]).toFixed(2):(data.datas[idx][2]).toFixed(2),
                  value: (vols/(i-idx+1)).toFixed(2)+' M'
              }, {
                  xAxis: i,
                  yAxis: data.datas[i][1]>data.datas[i][0]?(data.datas[i][3]).toFixed(2):(data.datas[i][2]).toFixed(2)
              }]);
              idx = i; vols = data.datas[i][4];
          }
      }
      return markLineData;
    }

  }
})
</script>

</body>
</html>